package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.bican.wordpress.Wordpress;
import redstone.xmlrpc.XmlRpcFault;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

import data.Data;

@SuppressWarnings("serial")
public class EditSitemapServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		DBObject dbObject = (DBObject) session.getAttribute("users");
		if(dbObject==null)
		{
			try {
				response.sendRedirect("/");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		String blog = (String) session.getAttribute("work");
		DBCollection collection = Data.data("urlCraw");
		DBCursor cursor=collection.find(new BasicDBObject("username",dbObject.get("username")).append("blogurl", blog));
		request.setAttribute("cursor", cursor);
		
		String[] listError = new String[5];
		request.setAttribute("listError", listError);
		
		String sitemap=request.getParameter("url");
		DBObject object=collection.findOne(new BasicDBObject("username",dbObject.get("username")).append("blogurl", blog).append("sitemap", sitemap));
		request.setAttribute("sitemap", object);
		
		DBCollection coll = Data.data("blogCraw");
		DBObject objectss = coll.findOne(new BasicDBObject("username",dbObject.get("username")).append("blogurl", blog));
		
		if(objectss.get("type").toString().equals("wordpress"))
		{
			ArrayList<String> category = Utils.returnCategory(objectss);
			request.setAttribute("category", category);
		}
		
		try {
			request.getRequestDispatcher("/edit_sitemap.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		DBObject dbObject = (DBObject) session.getAttribute("users");
		if(dbObject==null)
		{
			try {
				response.sendRedirect("/");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		String blog = (String) session.getAttribute("work");
		
		String sitemap = request.getParameter("sitemap");
		String oldsitemap = request.getParameter("oldsitemap");
		String reglink = request.getParameter("reglink");
		String regtitle = request.getParameter("regtitle");
		String regcontent = request.getParameter("regcontent");
		String regremove = request.getParameter("regremove");
		String type = request.getParameter("type");
		String typeLink = request.getParameter("typeLink");
		String source = request.getParameter("source");
		String source_type = request.getParameter("source_type");
		String category = request.getParameter("category");
		String tag = request.getParameter("tag");
		String translate = request.getParameter("translate");
		String rewriter_title = request.getParameter("rewriter_title");
		String language = request.getParameter("language");
		String sumtitlebefore = request.getParameter("sumtitlebefore");
		String sumtitleafter = request.getParameter("sumtitleafter");
		String source_image = request.getParameter("source_image");
		String remove_tag_a = request.getParameter("remove_tag_a");
		String contain = request.getParameter("contain");
		
		ArrayList<String> site = Utils.getStachSite();
		
		sitemap = Utils.fomatSitemap(sitemap);
		
		String[] listError = new String[5];
		if(sitemap!=null&&sitemap.equals(""))
			listError[0]="Url is not empty !";
		if(reglink!=null&&reglink.equals(""))
			listError[1]="Regexp get link is not empty !";
		if(regtitle!=null&&regtitle.equals(""))
			listError[2]="Regexp title  is not empty !";
		if(regcontent!=null&&regcontent.equals(""))
			listError[3]="Regexp content is not empty !";
		if(site.contains(Utils.fomatDmain(sitemap))&&tag!=null&&tag.equals(""))
			listError[1]="Tag is not empty !";
		
		DBCollection collection = Data.data("urlCraw");
		
		if(listError[0]==null&&listError[1]==null&&listError[3]==null&&listError[2]==null)
		{
			DBObject object = collection.findOne(new BasicDBObject("sitemap",oldsitemap).append("username", dbObject.get("username")).append("blogurl", blog));
			
			if(object!=null)
			{
				if(site.contains(Utils.fomatDmain(sitemap)))
				{
					sitemap="http://"+Utils.fomatDmain(sitemap)+"/questions/tagged/"+tag;
					object.put("tag", tag);
				}
				
				object.put("username", dbObject.get("username").toString());
				object.put("sitemap", sitemap);
				object.put("reglink", reglink);
				object.put("regtitle", regtitle);
				object.put("regcontent", regcontent);
				object.put("regremove", regremove);
				object.put("domain", Utils.fomatDmain(sitemap));
				object.put("type", type);
				object.put("typeLink", typeLink);
				object.put("source", source);
				object.put("source_type", source_type);
				object.put("category", category);
				object.put("blogurl", blog);
				object.put("translate", translate);
				object.put("rewriter_title", rewriter_title);
				object.put("language", language);
				object.put("sumtitlebefore", sumtitlebefore);
				object.put("sumtitleafter", sumtitleafter);
				object.put("time", new Date().getTime());
				object.put("source_image", source_image);
				object.put("remove_tag_a", remove_tag_a);
				object.put("contain", contain);
				
				collection.save(object);
				request.setAttribute("success", "Edit url success");
			} else {
				request.setAttribute("error", "Edit url false");
				sitemap = oldsitemap;
			}
		} else {
			request.setAttribute("error", "Edit url false");
			sitemap = oldsitemap;
		}
		
		DBObject object=collection.findOne(new BasicDBObject("username",dbObject.get("username")).append("blogurl", blog).append("sitemap", sitemap));
		request.setAttribute("sitemap", object);
		
		DBCursor cursor=collection.find(new BasicDBObject("username",dbObject.get("username")).append("blogurl", blog)).limit(100);
		request.setAttribute("cursor", cursor);
		
		
		request.setAttribute("listError", listError);
		request.setAttribute("post", "post");
		
		DBCollection coll = Data.data("blogCraw");
		DBObject objectss = coll.findOne(new BasicDBObject("username",dbObject.get("username")).append("blogurl", blog));
		
		if(objectss.get("type").toString().equals("wordpress"))
		{
			ArrayList<String> categoryss = Utils.returnCategory(objectss);
			request.setAttribute("category", categoryss);
			
			String[] listCategory = category.split(",");
			if(category!=null&&"".equals(category))
			{
				for (int i = 0; i < listCategory.length; i++) {
					int k=0;
					for (int j = 0; j < categoryss.size(); j++) {
						if(categoryss.get(j).equals(listCategory[i]))
						{
							k=1;
						}
					}
					if(k==0)
					{
						String username = objectss.get("usernameblog").toString();
					    String password = objectss.get("passwordblog").toString();
					    String xmlRpcUrl = objectss.get("blogurl").toString()+"/xmlrpc.php";
					    Wordpress wp = new Wordpress(username, password, xmlRpcUrl);
					    try {
							wp.newCategory(listCategory[i], listCategory[i], 0);
						} catch (XmlRpcFault e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
			
		}
		
		try {
			request.getRequestDispatcher("/edit_sitemap.jsp").forward(request,
					response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		}
}
